package top.jacktgq.web.servlet;
/**
 * @Author CandyWall
 * @Date 2021/6/20--12:33
 * @Description 处理学生信息的servlet
 */

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import top.jacktgq.dao.StudentDao;
import top.jacktgq.pojo.Student;
import top.jacktgq.utils.MapperUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

@WebServlet(name = "UpdateStudentAndUploadPhotoServlet", value = "/updateStudentAndUploadPhoto")
public class UpdateStudentAndUploadPhotoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);// 文件上传缓存大小设定，单位为byte
        String tempPath = this.getServletContext().getRealPath("temp");// 磁盘缓存文件保存路径设定，这里设置为项目下temp文件夹绝对路径
        factory.setRepository(new File(tempPath));// 这两项设定也可以在构造函数中表现

        // 2创建阿帕奇文件上传核心类
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 2.1判断form提交的是否是一个文件上传form
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                HashMap resultMap = new HashMap();
                String msg = "提交成功";
                Student student = new Student();
                // 2.2解析request为一个集合，元素为FileItem
                List<FileItem> parseRequest = upload.parseRequest(request);
                // 2.3设置解析到的文件名编码格式
                upload.setHeaderEncoding("UTF-8");
                // 2.4遍历解析集合，如果为文件，则
                for (FileItem fileItem : parseRequest) {
                    // 判断是否文件，结果为“true”就是普通表单，如果为“false”则是文件
                    if (fileItem.isFormField()) {
                        System.out.println(fileItem.getFieldName() + "-------" + fileItem.getString());
                        String fieldName = fileItem.getFieldName();
                        if (fieldName.equals("stu_id")) {
                            student.setStu_id(fileItem.getString());
                        } else if (fieldName.equals("name")) {
                            String name = fileItem.getString();
                            name = new String(name.getBytes(StandardCharsets.ISO_8859_1), "utf-8");
                            student.setName(name);
                        } else if (fieldName.equals("email")) {
                            student.setEmail(fileItem.getString());
                        } else if (fieldName.equals("birthdate")) {
                            try {
                                student.setBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse(fileItem.getString()));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        } else if (fieldName.equals("age")) {
                            student.setAge(Integer.parseInt(fileItem.getString()));
                        } else if (fieldName.equals("sex")) {
                            student.setSex(Integer.parseInt(fileItem.getString()));
                        } else if (fieldName.equals("phone")) {
                            student.setPhone(fileItem.getString());
                        }
                    } else {
                        String name = fileItem.getName();// 获取所上传文件的名称
                        InputStream in = fileItem.getInputStream();// 获得上传文件字节流
                        // BufferedInputStream bis = new BufferedInputStream(in);
                        // 创建输出文件
                        String outPath = this.getServletContext().getRealPath("temp/" + name);
                        FileOutputStream out = new FileOutputStream(new File(outPath));
                        // BufferedOutputStream bos = new BufferedOutputStream(out);
                        // 使用IOUtils工具输出， 也就是copy文件
//                        IOUtils.copy(in, out);
                        byte[] bytes = IOUtils.toByteArray(in);
                        student.setPhoto_byte(bytes);

                        // 文件上传完毕，清空缓存资料夹内容
                        in.close();
                        out.close();
                        fileItem.delete();
                    }
                }
                StudentDao studentService = new StudentDao();
                try {
                    studentService.editStudentAndUploadPhoto(student);
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("插入数据失败！");
                    msg = "提交失败！";
                }
                resultMap.put("code", 0);
                resultMap.put("msg", msg);
                /*HashMap<String, Object> data = new HashMap<>();
                data.put("src", dirName + "/" + newName);
                resultMap.put("data", data);*/
                response.getWriter().write(MapperUtils.mapToJson(resultMap));
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        } else {
            // 如果不是文件上传类型，则采用普通表单获取方式
            System.out.println("不是文件上传表单！");
        }
//        Boolean ifSucceed = studentService.setCurriculumInfo(curriculumInfo);
//        response.getWriter().write("{\"ifSucceed\":"+ifSucceed+"}");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
